package com.cz.mes.view;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateDbTableName {
    public static void main(String[] args) {
        String dbGroup = "uat3";
        try {
            int tableId = 8;
            String tableNameIn = "in ('production_material','production_material_detail')";


            String sql = "select * from mes_vw_column where table_id =:tableId and status =1";
            Map<String, Object> params1 = new HashMap<>();
            params1.put("tableId", tableId);
            List<Entity> entityList = Db.use(dbGroup).query(sql,params1);
            for (Entity entity : entityList) {
                String columnId = entity.getStr("id");

                String dbColumnName = entity.getStr("db_column_name");
                if (StrUtil.indexOfIgnoreCase(dbColumnName, ".") != -1) {
                    dbColumnName = StrUtil.subAfter(dbColumnName, ".", true);
                }
                String sql1 = "SELECT TABLE_NAME,COLUMN_NAME, COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'mesdb' AND COLUMN_NAME = :columnName AND TABLE_NAME "+tableNameIn;
                Map<String,Object> params = new HashMap<>();
                params.put("columnName",dbColumnName);
                Entity columnEntity = Db.use(dbGroup).queryOne(sql1,params);
                if(columnEntity!=null){
                    String tableName = columnEntity.getStr("TABLE_NAME");
                    System.out.println(tableName);

                    String sql2  = "UPDATE mes_vw_column SET db_table_name = :tableName WHERE id = :columnId";
                    Map<String,Object> updateParams = new HashMap<>();
                    updateParams.put("columnId",columnId);
                    updateParams.put("tableName",tableName);
                    Db.use(dbGroup).execute(sql2,updateParams);
                    System.out.println(columnId);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
